<!-- p_purchase.ftl 采购单 -->
var Msales = {
    editIndex: -1,
    orderStatus: 0,
    unitArr: []
};

$.extend($.fn.datagrid.defaults.editors, {
    house: {
        init: function (container, options) {
            return $('<div style="text-align: center">编辑</div>').appendTo(container);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            var rows = Msales.dtable.datagrid("getRows");
            var house = rows[Msales.editIndex].house;
            return house;
        },
        setValue: function (target, value) {
        },
        resize: function (target, width) {
            $(target).click(function () {
                Msales.isDg = 1;
                var rows = Msales.dtable.datagrid("getRows");
                var skuId = rows[Msales.editIndex].skuId;
                var house = rows[Msales.editIndex].house;
                var count = rows[Msales.editIndex].count;
                var href = "/wWearhouse/treeGrid?skuId=" + skuId + "&house=" + house + "&type=0";//type 0出库 1入库
                var $dg = $yd.win.create('仓库/库位/批次', href);
                $dg.width = "450px;";
                $dg.height = "520px;";
                $dg.open(function (that, $win) {

                }, function (that, $win) {
                    var data = KW.getResult();
                    if (data != "error") {
                        Msales.dtable.datagrid('updateRow', {
                            index: Msales.editIndex,
                            row: {
                                house: data
                            }
                        });

                        that.close();
                        Msales.isDg = 0;
                    }
                }, function () {
                    if (Msales.editIndex > -1) {
                        Msales.dtable.datagrid('endEdit', Msales.editIndex);
                    }
                    Msales.editIndex = -1;
                    Msales.isDg = 0;
                });
            });

            $(target)._outerWidth(width);
        }
    }
});

Msales.dg = function () {
    $.ajax({
        type: "POST",
        url: "/sysDict/materiel_MU",
        dataType: "json",
        success: function (data) {
            Msales.unitArr = data;
        }
    });

    Msales.dtable = $('#mSales_table');
    //var ckTitle = Msales.orderStatus == 0 ? "<span style=\"color:blue\">仓库/库位/批号</span><span style='color:red'>*</span>" : "仓库/库位/批号";
    Msales.dtable.datagrid({
        url: "/mSales/detailList?salesId=" + $("#salesId").val(),
        fitColumns: true,
        autoRowHeight: true,
        rownumbers: true,
        singleSelect: false,
        columns: [[
            {field: 'skuId', hidden: true},//规格id
            {field: 'id', hidden: true},//明细 id
            {field: 'goodsName', title: '商品名称', width: 150},
            {field: 'skus', title: '规格', width: 200},
            {field: 'skuCode', title: '商品编号', width: 80},
            {
                field: 'unit', title: '单位', width: 80, formatter: function (value, row, index) {
                    for (var i = 0; i < Msales.unitArr.length; i++) {
                        if (value == Msales.unitArr[i].id) {
                            return Msales.unitArr[i].text;
                        }
                    }
                    return value;
                }
            },
            {field: 'skuNum', title: '库存数量', width: 80},
            // {
            //     field: 'wearhouseName',
            //     title: '仓库',
            //     width: 200,
            //     // editor: {type: 'house'},
            //     formatter: function (value, row, index) {
            //         if (Msales.isEmpty(value)) {
            //             return "";
            //         }
            //         var arr = value.split(",");
            //         var result = "";
            //         var first = "";
            //         for (var i = 0; i < arr.length; i++) {
            //             var arr2 = arr[i].split("_");
            //             result += arr2[1] + " " + arr2[3] + " " + arr2[4] + " X " + arr2[6] + "\n"
            //             if (first == "") {
            //                 first += arr2[1] + " " + arr2[3] + " " + arr2[4] + " X " + arr2[6];
            //             }
            //         }
            //         return "<a title='" + result + "'>" + first + (arr.length > 1 ? "..." : "") + "</a>";
            //     }
            // },
            {
                field: 'sellPrice', title: '参考售价', width: 80, formatter: function (value, row, index) {
                    return Number(value).toFixed(2);
                }
            },
            {
                field: 'price',
                title: '销售价',
                width: 80, formatter: function (value, row, index) {
                    return Number(value).toFixed(2);
                }
            },
            {
                field: 'count',
                title: '数量',
                width: 80
            },
            {
                field: 'shouldPay', title: '总金额', width: 80, formatter: function (value, row, index) {
                    return Number(value).toFixed(2);
                }
            },
            {field: 'remark', title: '备注', width: 80},
        ]],
        onClickRow: function (index, row) {
            Msales.dtable.datagrid("unselectAll");
        },
        onClickCell: function (index, field) {
            if (Msales.orderStatus != 0) {
                return;
            }
            if (Msales.editIndex != index) {
                if (Msales.editIndex > -1) {
                    Msales.dtable.datagrid('endEdit', Msales.editIndex);
                }
                Msales.editIndex = index;
            }
            if (field == "house") {
                Msales.dtable.datagrid('beginEdit', index);
            }
        }
    });

    if (Msales.orderStatus == 0) {
        Msales.dtable.datagrid('enableCellEditing');
    }
};

Msales.refresh = function () {
    window.location.reload();
};
Msales.changePayFee = function (newValue, oldValue) {
    if (newValue == "") {
        $("#payFee").numberbox("setValue", 0);
        return;
    }
    if (Number(newValue) > Number($("#payingFee").val())) {
        $yd.alert("本次付款金额不能大于剩余待付！", function () {
            $("#payFee").numberbox("setValue", $("#payingFee").val());
        });
    }
};

Msales.isEmpty = function (value) {
    if (value == undefined || value == null || value == "") {
        return true;
    }
    return false;
}

Msales.save = function () {
    //结束编辑状态
    if (Msales.editIndex != undefined && Msales.editIndex != -1) {
        Msales.dtable.datagrid('endEdit', Msales.editIndex);
    }

    $('#myForm').form('submit', {
        url: "/mSales/outRepo",
        onSubmit: function () {
            var isValid = $(this).form('validate');//只能校验处于编辑状态的栏位
            if (!isValid) {
                return isValid;
            }

            //校验数据
            var rows = Msales.dtable.datagrid("getRows");
            if (rows.length == 0) {
                $yd.alert("请添加商品");
                return false;
            }

            for (var i = 0; i < rows.length; i++) {
                var row = rows[i];
                if (Number(row.count) > Number(row.skuNum)) {
                    $yd.alert("第" + (i + 1) + "行：销售数量不能大于当前库存");
                    return false;
                }
            }

            // for (var i = 0; i < rows.length; i++) {
            //     var row = rows[i];
            //     var house = row.house;
            //     // if (Msales.isEmpty(house)) {
            //     //     $yd.alert("第" + (i + 1) + "行：未配置仓库/库位");
            //     //     return false;
            //     // }
            //     var total = 0;
            //     var arr = house.split(",");
            //     for (var j = 0; j < arr.length; j++) {
            //         total += Number(arr[j].split("_")[6]);
            //     }
            //     if (total != row.count) {
            //         $yd.alert("第" + (i + 1) + "行：出库总数量必须等于销售数量");
            //         return false;
            //     }
            // }

            if (Number($("#payFee").val()) > Number($("#totalFee").val())) {
                $yd.alert("本次付款金额不能大于应付总额！", function () {
                    $("#payFee").numberbox("setValue", 0);
                });
                return false;
            }

            //封装数据
            $("#goods").val(JSON.stringify(rows));
            return isValid;
        },
        success: function (data) {
            var d = $.parseJSON(data);
            if (d.code == 0) {
                if(d.message == "success") {
                    $yd.alert("出库成功", function () {
                        window.location.reload();
                    });
                } else {
                    $yd.alert(d.message);
                }
            }
        }
    });
};

// 处理按钮
Msales.btn = function () {
    if (Msales.orderStatus == 0) {
        var sb = new $yd.SearchBtn($(Msales.obtn));
        sb.create('save green', '发货', Msales.save);
    }
};

Msales.dg2 = function () {
    Msales.ptable = $('#pay_table');
    Msales.ptable.datagrid({
        url: "/mSales/payDetailList?salesId=" + $("#salesId").val(),
        fitColumns: true,
        autoRowHeight: true,
        rownumbers: true,
        singleSelect: false,
        columns: [[
            {field: 'ctime', title: '日期', width: 80},
            {field: 'amount', title: '本次付款', width: 80, formatter: function (value, row, index) {
                    return Number(value).toFixed(2);
                }},
            {field: 'remain_amount', title: '剩余未结算', width: 80},
            {field: 'type_name', title: '结算方式', width: 80},
            {field: 'username', title: '操作人', width: 80},
            {field: 'remark', title: '备注', width: 80}
        ]]
    });
};

Msales.pay = function () {
    var salesId = $("#salesId").val();
    var payFee = $("#payFee").val();
    var payType = $("#payType").val();
    var payRemark = $("#payRemark").val();
    if (Number(payFee) == 0) {
        $yd.alert("付款金额不能为0");
        return;
    }

    $.post("/mSales/pay", {
        salesId: salesId,
        payType: payType,
        payFee: payFee,
        payRemark: payRemark
    }, function (data) {
        if (data.code == 0) {
            $yd.alert("支付成功", function () {
                Msales.refresh();
            });
        }
    });
};

$(function () {
    Msales.orderStatus = $("#orderStatus").val();

    Msales.obtn = '#mSales_btn';
    Msales.dg(); // 数据表格
    Msales.btn(); // 初始化按钮
    Msales.dg2(); // 数据表格

    //默认值
    $("input[name='orderStatus']").combobox({
        url: "/sysDict/sales_order_status",
        panelHeight: 'auto',
        required: true,
        valueField: 'id',
        textField: 'text'
    });

    $("input[name='payType']").combobox({
        url: "/sysDict/pay_type",
        panelHeight: 'auto',
        editable: false,
        required: true,
        valueField: 'id',
        textField: 'text',
        onLoadSuccess: function () {
            var d = $(this).combobox("getData");
            $(this).combobox("setValue", d[0].value);
        }
    });
});